/*
 * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.micode.notes.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.view.Window;
import android.view.WindowManager;

import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.DataUtils;

import java.io.IOException;

public class AlarmAlertActivity extends Activity implements DialogInterface.OnClickListener, DialogInterface.OnDismissListener {
    private long mNoteId; // 关联闹钟的笔记ID
    private String mSnippet; // 笔记的摘要
    private static final int SNIPPET_PREW_MAX_LEN = 60; // 摘要最大长度
    MediaPlayer mPlayer; // 媒体播放器实例

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE); // 请求无标题窗口

        final Window win = getWindow();
        win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); // 确保在锁定屏幕时显示窗口

        // 如果屏幕未开启，设置相应的窗口标志
        if (!isScreenOn()) {
            win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                    | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                    | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
                    | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR);
        }

        Intent intent = getIntent(); // 获取传入的意图

        try {
            // 从意图中获取笔记ID
            mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1));
            // 根据笔记ID获取摘要
            mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId);
            // 如果摘要过长，截断并添加信息
            mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0,
                    SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info)
                    : mSnippet;
        } catch (IllegalArgumentException e) {
            e.printStackTrace(); // 捕获异常并打印堆栈跟踪
            return;
        }

        mPlayer = new MediaPlayer(); // 创建新的媒体播放器实例
        // 如果笔记在数据库中可见，显示对话框并播放闹钟声音
        if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) {
            showActionDialog();
            playAlarmSound();
        } else {
            finish(); // 否则结束活动
        }
    }

    // 检查屏幕是否开启
    private boolean isScreenOn() {
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        return pm.isScreenOn();
    }

    // 播放闹钟声音
    private void playAlarmSound() {
        Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM); // 获取默认闹钟铃声

        // 检查静音模式设置
        int silentModeStreams = Settings.System.getInt(getContentResolver(),
                Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);

        if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) {
            mPlayer.setAudioStreamType(silentModeStreams); // 设置音频流类型
        } else {
            mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
        }
        try {
            mPlayer.setDataSource(this, url); // 设置数据源为闹钟铃声
            mPlayer.prepare(); // 准备播放器
            mPlayer.setLooping(true); // 设置为循环播放
            mPlayer.start(); // 开始播放
        } catch (IllegalArgumentException | SecurityException | IllegalStateException | IOException e) {
            e.printStackTrace(); // 捕获并打印异常
        }
    }

    // 显示操作对话框
    private void showActionDialog() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle(R.string.app_name); // 设置对话框标题
        dialog.setMessage(mSnippet); // 设置对话框消息为笔记摘要
        dialog.setPositiveButton(R.string.notealert_ok, this); // 设置确定按钮
        if (isScreenOn()) {
            dialog.setNegativeButton(R.string.notealert_enter, this); // 设置取消按钮（如果屏幕开启）
        }
        dialog.show().setOnDismissListener(this); // 显示对话框并设置消失监听器
    }

    // 处理对话框按钮点击事件
    public void onClick(DialogInterface dialog, int which) {
        switch (which) {
            case DialogInterface.BUTTON_NEGATIVE:
                // 如果点击了取消按钮，打开笔记编辑活动
                Intent intent = new Intent(this, NoteEditActivity.class);
                intent.setAction(Intent.ACTION_VIEW);
                intent.putExtra(Intent.EXTRA_UID, mNoteId);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    // 处理对话框消失事件
    public void onDismiss(DialogInterface dialog) {
        stopAlarmSound(); // 停止闹钟声音
        finish(); // 结束活动
    }

    // 停止闹钟声音
    private void stopAlarmSound() {
        if (mPlayer != null) {
            mPlayer.stop(); // 停止播放
            mPlayer.release(); // 释放资源
            mPlayer = null; // 清空播放器引用
        }
    }
}